<template>
  <view class="container">
    <!-- 搜索区域 -->
    <view class="search-area">
      <view class="search-row">
        <!-- 状态筛选 -->
        <view class="status-picker">
          <picker mode="selector" :range="statusOptions" range-key="dictLabel" @change="handleStatusChange" class="picker">
            <view class="picker-text">{{currentStatus.dictLabel || '全部'}}</view>
          </picker>
        </view>
        
        <!-- 岗位名称搜索 -->
        <view class="search-box">
          <input 
            type="text" 
            class="search-input" 
            placeholder="请输入岗位名称"  
            confirm-type="search"
            v-model="searchJobName"
            @confirm="handleSearch"
          />
          <text class="clear-icon" v-if="searchJobName" @tap="clearSearch">✕</text>
        </view>
        <view class="search-btn" @tap="handleSearch">搜索</view>
      </view>
    </view>

    <!-- 可滚动区域：意向岗位列表 -->
    <scroll-view 
      scroll-y 
      class="job-list" 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="job-card" v-for="(item, index) in jobList" :key="index" @tap="goToDetail(item)">
        <view class="job-header">
          <view class="job-title">{{item.jobName}}</view>
          <view class="job-salary">{{item.salary || '面议'}}</view>
        </view>
        <view class="job-company">{{item.companyName}}</view>
        <view class="job-info">
          <text class="job-tag job-address-tag" v-if="item.jobAddress">
            <text class="job-address-icon iconfont icon-location"></text>
            {{item.jobAddress}}
          </text>
          <text class="job-tag">{{getCompanyTypeText(item.companyType)}}</text>
          <text class="job-tag degree-tag">{{getDegreeText(item.degree)}}</text>
          <text class="job-tag" v-if="item.type !== undefined && item.type !== null && item.type !== ''">{{getTypeText(item.type)}}</text>
          <text class="job-tag" v-if="item.isWeave !== undefined && item.isWeave !== ''">{{getYesNoText(item.isWeave) === '是' ? '带编' : '不带编'}}</text>
        </view>
        <!-- 添加报名状态和时间 -->
        <view class="job-status">
          <view class="job-application-time" v-if="item.startDate || item.endDate">
            <text class="job-time-label">报名时间：</text>
            <text class="job-time-value">{{ item.startDate && item.endDate ? `${item.startDate} ~ ${item.endDate}` : (item.endDate || '暂无') }}</text>
          </view>
          <text :class="['status-tag', getStatusClass(item.status)]">{{getStatusText(item.status)}}</text>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="jobList.length > 0">
        <text v-if="isLoading">加载中...</text>
        <text v-else-if="!hasMore">没有更多数据了</text>
      </view>
      
      <!-- 空状态提示 -->
      <view class="empty-state" v-if="jobList.length === 0 && !isLoading">
        <text class="empty-text">暂无意向岗位</text>
        <view class="reset-filter-btn" @tap="resetAllFilters">重置筛选条件</view>
      </view>
    </scroll-view>
  </view>
</template> 

<script>
import { getLikeJobList } from '@/api/job/recruitJob.js'
import { getDicts } from '@/api/dict/data.js'

export default {
  data() {
    return {
      jobList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      isLoading: false,
      isRefreshing: false,
      hasMore: true,
      searchJobName: '', // 岗位名称搜索关键词
      
      // 公司类型字典名称
      companyTypeDictType: 'recruit_company_type',
      // 公司类型字典
      companyTypeDict: [],
      // 学历要求字典名称
      degreeDictType: 'recruit_degree',
      // 学历要求字典
      degreeDict: [],
      // 招聘类型字典名称
      typeDictType: 'recruit_type',
      // 招聘类型字典
      typeDict: [],
      // 招聘是否字典名称
      yesOrNoDictType: 'recruit_yes_no',
      // 招聘是否字典
      yesOrNoDict: [],
      // 报名状态字典名称
      statusDictType: 'recruit_notice_status',
      // 报名状态字典
      statusDict: [],
      // 报名状态选项（将在加载字典后更新）
      statusOptions: [
        { dictValue: '', dictLabel: '全部' }
      ],
      currentStatus: { dictValue: '', dictLabel: '全部' },
      showFilter: false,
      statusBarHeight: 0
    }
  },
  async onLoad() {
    // 获取状态栏高度，适配不同机型
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    
    // 加载字典数据
    await this.loadDictData();
    
    // 加载意向岗位列表
    this.fetchJobList();
  },
  methods: {
    // 重置所有筛选条件
    resetAllFilters() {
      // 显示加载提示
      uni.showLoading({
        title: '重置中...'
      });
      
      // 重置搜索关键词
      this.searchJobName = '';
      
      // 重置状态筛选
      this.currentStatus = { dictValue: '', dictLabel: '全部' };
      
      // 重置页码
      this.pageNum = 1;
      
      // 重新获取数据
      this.fetchJobList(true).finally(() => {
        uni.hideLoading();
        uni.showToast({
          title: '已重置筛选条件',
          icon: 'success',
          duration: 1500
        });
      });
    },
    
    showFilterPanel() {
      this.showFilter = true
    },
    // 处理状态选择变化
    handleStatusChange(e) {
      const index = e.detail.value
      this.currentStatus = this.statusOptions[index]
      this.pageNum = 1
      this.jobList = []
      this.hasMore = true
      this.fetchJobList(true)
    },
    
    // 处理搜索
    handleSearch() {
      this.pageNum = 1
      this.jobList = []
      this.hasMore = true
      this.fetchJobList(true)
    },
    
    // 清除搜索内容
    clearSearch() {
      this.searchJobName = ''
      this.pageNum = 1
      this.jobList = []
      this.hasMore = true
      this.fetchJobList(true)
    },

    // 获取状态文本
    getStatusText(value) {
      if (!value && value !== 0) return '未知状态';
      const dictValue = String(value);
      if (this.statusDict && this.statusDict.length > 0) {
        const dictItem = this.statusDict.find(item => item.dictValue == dictValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      
      // 回退到基础状态文本
      const statusMap = {
        3: '即将报名',
        1: '正在报名',
        2: '即将截止',
        4: '结束报名'
      };
      return statusMap[value] || '未知状态';
    },

    // 获取状态样式类
    getStatusClass(value) {
      const classMap = {
        3: 'status-upcoming',    // 即将报名
        1: 'status-ongoing',     // 正在报名
        2: 'status-ending',      // 即将截止
        4: 'status-ended'        // 结束报名
      }
      return classMap[value] || ''
    },

    // 获取公司类型文本
    getCompanyTypeText(value) {
      if (!value && value !== 0) return '不限';
      const dictValue = String(value);
      if (this.companyTypeDict && this.companyTypeDict.length > 0) {
        const dictItem = this.companyTypeDict.find(item => item.dictValue == dictValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      return '不限';
    },
    
    // 获取学历文本
    getDegreeText(value) {
      if (!value && value !== 0) return '不限';
      const dictValue = String(value);
      if (this.degreeDict && this.degreeDict.length > 0) {
        const dictItem = this.degreeDict.find(item => item.dictValue == dictValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      return '不限';
    },
    
    // 获取招聘类型文本
    getTypeText(value) {
      console.log('招聘类型值:', value, '类型:', typeof value);
      if (value === undefined || value === null || value === '') return '不限';
      
      // 招聘类型可能是数字或字符串，尝试直接比较
      if (this.typeDict && this.typeDict.length > 0) {
        // 先尝试直接比较
        let dictItem = this.typeDict.find(item => item.dictValue == value);
        
        // 如果没找到，尝试转换为字符串再比较
        if (!dictItem) {
          const dictValue = String(value);
          console.log('转换后的招聘类型dictValue:', dictValue);
          dictItem = this.typeDict.find(item => String(item.dictValue) === dictValue);
        }
        
        console.log('找到的招聘类型字典项:', dictItem);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      
      // 如果字典中找不到，返回默认值
      return value === 1 ? '社会招聘' : value === 2 ? '校园招聘' : '不限';
    },
    
    // 获取是否文本
    getYesNoText(value) {
      if (!value && value !== 0) return '不限';
      const dictValue = String(value);
      if (this.yesOrNoDict && this.yesOrNoDict.length > 0) {
        const dictItem = this.yesOrNoDict.find(item => item.dictValue == dictValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      return value == 1 ? '是' : value == 0 ? '否' : '不限';
    },

    // 获取意向岗位列表数据
    async fetchJobList(isRefresh = false) {
      if (this.isLoading) {
        return
      }
      
      this.isLoading = true
      
      if (isRefresh) {
        this.pageNum = 1
        this.jobList = []
        this.hasMore = true
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          status: this.currentStatus.dictValue,
          jobName: this.searchJobName.trim() // 添加岗位名称搜索参数
        }
        
        const res = await getLikeJobList(params)
        
        if (res.code === 200) {
          const { rows, total } = res
          
          if (isRefresh) {
            this.jobList = rows
          } else {
            this.jobList = [...this.jobList, ...rows]
          }
          
          // 调试输出第一个岗位信息
          if (rows && rows.length > 0) {
            console.log('第一个岗位数据:', rows[0]);
            console.log('招聘类型值:', rows[0].type);
          }
          
          this.total = total
          this.hasMore = this.jobList.length < total
          
          if (this.jobList.length === 0) {
            this.hasMore = false
          }
        } else {
          uni.showToast({
            title: res.msg || '获取数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载数据失败', error)
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        this.isRefreshing = false
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      await this.fetchJobList(true)
    },
    
    // 加载更多
    loadMore() {
      if (!this.hasMore || this.isLoading) {
        return
      }
      
      if (this.jobList.length < this.pageSize) {
        this.hasMore = false
        return
      }
      
      this.pageNum++
      this.fetchJobList()
    },
    
    // 跳转到详情页
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/job/detail?jobId=${item.jobId}`
      })
    },
    
    // 加载字典数据
    async loadDictData() {
      try {
        // 并行加载所有字典数据
        const [companyTypeRes, degreeRes, typeRes, yesOrNoRes, statusRes] = await Promise.all([
          getDicts(this.companyTypeDictType),
          getDicts(this.degreeDictType),
          getDicts(this.typeDictType),
          getDicts(this.yesOrNoDictType),
          getDicts(this.statusDictType)
        ]);
        
        // 设置字典数据
        if (companyTypeRes.code === 200) {
          this.companyTypeDict = companyTypeRes.data;
          console.log('公司类型字典数据:', this.companyTypeDict);
        }
        
        if (degreeRes.code === 200) {
          this.degreeDict = degreeRes.data;
          console.log('学历字典数据:', this.degreeDict);
        }
        
        if (typeRes.code === 200) {
          this.typeDict = typeRes.data;
          console.log('招聘类型字典数据:', this.typeDict);
          // 详细输出每个招聘类型项
          if (this.typeDict && this.typeDict.length > 0) {
            this.typeDict.forEach(item => {
              console.log(`招聘类型: dictValue=${item.dictValue}(${typeof item.dictValue}), dictLabel=${item.dictLabel}`);
            });
          }
        }
        
        if (yesOrNoRes.code === 200) {
          this.yesOrNoDict = yesOrNoRes.data;
          console.log('是否字典数据:', this.yesOrNoDict);
        }
        
        if (statusRes.code === 200) {
          this.statusDict = statusRes.data;
          console.log('报名状态字典数据:', this.statusDict);
          
          // 更新状态选项
          this.statusOptions = [
            { dictValue: '', dictLabel: '全部' },
            ...this.statusDict
          ];
        }
      } catch (error) {
        console.error('加载字典数据失败', error);
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100vh;
}

/* 搜索区域样式 */
.search-area {
  position: fixed;
  top: var(--status-bar-height-10px);
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 24rpx;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  width: 100%;
  min-height: 110rpx;
  display: flex;
  flex-direction: column;
}

/* 搜索行样式 */
.search-row {
  display: flex;
  align-items: center;
}

.status-picker {
  width: 240rpx;
  height: 70rpx;
  background-color: #f5f7fa;
  border-radius: 8rpx;
  margin-right: 20rpx;
  padding: 0 10rpx;
  box-sizing: border-box;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  height: 70rpx;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-right: 20rpx;
  box-sizing: border-box;
}

.search-icon {
  font-size: 28rpx;
  color: #999;
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  color: #333;
}

.clear-icon {
  font-size: 24rpx;
  color: #999;
  padding: 10rpx;
}

.search-btn {
  width: 120rpx;
  height: 70rpx;
  background-color: #409EFF;
  color: #fff;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
}

.picker {
  width: 100%;
  height: 70rpx;
}

.picker-text {
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
}

.job-list {
  flex: 1;
  margin-top: calc(var(--status-bar-height) + 80rpx);
  height: calc(100vh - var(--status-bar-height) - 80rpx);
  padding: 10rpx 5rpx;
  box-sizing: border-box;
}

.job-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 15rpx 24rpx;
  margin-bottom: 15rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
  
  &:active {
    transform: scale(0.98);
  }
}

.job-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;
  align-items: center;
}

.job-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.job-salary {
  font-size: 32rpx;
  color: #ff7043;
  font-weight: bold;
}

.job-company {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.job-info {
  display: flex;
  flex-wrap: wrap;
}

.job-tag {
  background: #f0f2f5;
  color: #666;
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  margin-right: 16rpx;
  margin-bottom: 8rpx;
}

.degree-tag {
  background: #e3f2fd;
  color: #1976d2;
}

.job-address-tag {
  display: flex;
  align-items: center;
  background: #f0f2f5;
  color: #666;
  max-width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.job-address-icon {
  margin-right: 8rpx;
  font-size: 24rpx;
  color: #999;
  display: inline-flex;
}

// 状态标签样式
.job-status {
  margin-top: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16rpx;
  border-top: 1rpx solid #f5f5f5;
}

// 报名时间样式
.job-application-time {
  font-size: 24rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.job-time-label {
  color: #999;
  margin-right: 4rpx;
}

.job-time-value {
  color: #333;
}

.status-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 6rpx;
}

.status-upcoming {
  background: #e3f2fd;
  color: #1976d2;
}

.status-ongoing {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-ending {
  background: #fff3e0;
  color: #f57c00;
}

.status-ended {
  background: #f5f5f5;
  color: #757575;
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.reset-filter-btn {
  margin-top: 20rpx;
  padding: 16rpx 40rpx;
  background-color: #409EFF;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: inline-block;
}
</style>
